from django.utils.decorators import method_decorator

from gis.common import track_logging
from gis.common.django_ext.decorators import validate_parameters
from gis.common.django_ext.views import BaseView
from itpay.core.agency import receipt_service
from itpay.core.conf import conf_client
from itpay.core.recharge_order import order_service
from itpay.core.recharge_order.const import RechargeSourceType
from .recharge_order_form import AddOrderSchema

_LOGGER = track_logging.getLogger(__name__)


class OrderListView(BaseView):
    @method_decorator(validate_parameters(AddOrderSchema))
    def post(self, request, cleaned_data):
        agency_ids = conf_client.get_dict("our_agency_ids")
        if int(cleaned_data["mch_id"]) == 88802:
            agency_ids = [10109]
        elif int(cleaned_data["mch_id"]) == 88803:
            agency_ids = [10110]

        receipt_address = receipt_service.random_receipt(
            agency_ids,
            cleaned_data["mch_id"],
            cleaned_data["user_id"],
            cleaned_data["pay_type"],
            recharge_success_amount=cleaned_data.get("recharge_success_amount"),
        )

        if "recharge_success_amount" in cleaned_data:
            del cleaned_data["recharge_success_amount"]

        return order_service.create_order(
            agency_id=receipt_address["agency_id"],
            **cleaned_data,
            receipt_address_id=receipt_address["id"],
            source=RechargeSourceType.OPERATION_CONSOLE
        )
